<template>
  <div style="position: relative">
    <el-form
      :inline="true"
      size="mini"
      :model="formInline"
      label-position="right"
    >
      <el-form-item label="合同名称">
        <el-input
          class="filter-item"
          v-model="formInline.contractName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="合同编号">
        <el-input
          class="filter-item"
          v-model="formInline.contractCode"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker
          v-model="times"
          type="daterange"
          align="right"
          unlink-panels
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="selecttime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="企业电话">
        <el-input
          class="filter-item"
          v-model="formInline.telephone"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="合同状态">
        <el-select
          v-model="formInline.verifyStatus"
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="会审审批中" value="1"></el-option>
          <el-option label="会审审批通过" value="2"></el-option>
          <el-option label="会审审批驳回" value="3"></el-option>
          <el-option label="盖章审批中" value="4"></el-option>
          <el-option label="盖章审批驳回" value="5"></el-option>
          <el-option label="审批完成" value="6"></el-option>
          <el-option label="待归档" value="7"></el-option>
          <el-option label="归档中" value="8"></el-option>
          <el-option label="归档驳回" value="9"></el-option>
          <el-option label="已完成" value="10"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="onSubmit">搜索</el-button>
        <el-button
          type="warning"
          class="el-button--reset"
          icon="el-icon-refresh-right"
          @click="resetFromdata"
          size="mini"
        ></el-button>
        <el-button type="primary" size="mini" @click="addFromdata"
          >创建合同</el-button
        >
        <el-button type="primary" size="mini" @click="exportForm"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <div class="total">
          <div
            class="total-item"
            :class="{ active: !formInline.verifyStatus }"
            @click="handleClickTotal('')"
          >
            全部（{{ countInfo.all || 0 }}）
          </div>
          <div
            class="total-item"
            :class="{ active: formInline.verifyStatus == '6' }"
            @click="handleClickTotal('6')"
          >
            审批完成（{{ countInfo.Approved || 0 }}）
          </div>
          <div
            class="total-item"
            :class="{ active: formInline.verifyStatus == '7' }"
            @click="handleClickTotal('7')"
          >
            待归档（{{ countInfo.TobeArchived || 0 }}）
          </div>
          <div
            class="total-item"
            :class="{ active: formInline.verifyStatus == '10' }"
            @click="handleClickTotal('10')"
          >
            已完成（{{ countInfo.Completed || 0 }}）
          </div>
        </div>
        <el-table
          :data="tableData"
          size="mini"
          style="width: 100%"
          header-cell-class-name="table-header-gray"
          v-loading="isShowloading"
        >
          <el-table-column
            type="index"
            align="center"
            width="55"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="contractName"
            align="center"
            width="150"
            label="合同名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="contractCode"
            align="center"
            width="100"
            label="合同编码"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="enterpriseName"
            align="center"
            label="企业名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="telephone"
            align="center"
            label="企业电话"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="contractStatusName"
            align="center"
            label="合同状态"
            show-overflow-tooltip
          >
            <template slot-scope="{ row }">
              {{ row.verifyStatus | statusFilter }}
            </template>
          </el-table-column>
          <el-table-column
            prop="regionName"
            align="center"
            label="所在地区"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="businessTypeName"
            align="center"
            label="业务类型"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{scope.row.businessNameList&&scope.row.businessNameList.length>0?scope.row.businessNameList.toString():''}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="createUserName"
            align="center"
            label="创建人"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="160"
          >
            <template slot-scope="scope">
              <!-- showContract 1显示 2隐藏 -->
              <el-button
                type="text"
                v-if="
                  scope.row.createUser === getUserInfo.userId &&
                  scope.row.verifyStatus === 2
                "
                @click="sealApplication(scope.row)"
                >盖章申请</el-button
              >
              <!-- showArchive 1显示 2隐藏 -->
              <el-button
                type="text"
                v-if="
                  scope.row.createUser === getUserInfo.userId &&
                  (scope.row.verifyStatus === 7 || scope.row.verifyStatus === 9)
                "
                @click="contractArchive(scope.row)"
                >归档</el-button
              >
              <el-button type="text" @click="handleInfo(scope.row)"
                >详情</el-button
              >
              <el-button
                type="text"
                @click="handleEdit(scope.row)"
                v-if="
                  scope.row.showEditor === 1 && scope.row.verifyStatus < 7
                "
                >修改</el-button
              >
              <el-button
                type="text"
                @click="handleDelete(scope.row)"
                v-if="
                  scope.row.showDelete === 1 && scope.row.verifyStatus < 7
                "
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-size="page_size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="total"
          ></el-pagination>
        </el-row>
      </el-col>
    </el-row>
    <!-- 盖章申请弹窗 -->
    <el-dialog title="添加审批人" :visible.sync="approver.show">
      <Approver
        :approverList="approver.list"
        @handleChooseapprover="handleChooseapprover"
      ></Approver>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approver.show = false">取 消</el-button>
        <el-button type="primary" @click="confirmApprover">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Contracts } from '@/api/projectAdministration.js';
import { Businesstype } from '@/api/business.js';
import Approver from './components/approver.vue';
import ContractArchive from './components/contractArchive.vue';
export default {
  name: 'Contracts',
  components: {
    Approver
  },
  filters: {
    statusFilter (val) {
      const data = {
        1: '会审审批中',
        2: '会审审批通过',
        3: '会审审批驳回',
        4: '盖章审批中',
        5: '盖章审批驳回',
        6: '审批完成',
        7: '待归档',
        8: '归档中',
        9: '归档驳回',
        10: '已完成'
      }
      return data[val]
    }
  },
  data () {
    return {
      editDialogVisible: false,
      formInline: {
        contractName: null,
        contractCode: null,
        projectName: null,
        customerName: null,
        paymentMethod: null,
        signingDateFrom: null,
        signingDateTo: null,
        businessType: null,
        verifyStatus: null
      },
      showDetail: {},
      showEdit: {},
      tableData: [],
      villageData: [],
      total: 0,
      page_size: 10,
      pageNo: 1,
      isShowloading: false,
      businesstypeTree: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      Addroptions: [],
      defaultProps: {
        children: 'nodes',
        label: 'name'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      times: '',
      countInfo: {},
      // 选择审批人相关
      approver: {
        show: false,
        selectRow: '',
        list: []
      }
    }
  },
  created () {
    this.loadbusinesstypeTree();
  },
  activated: function () {
    this.loadContractsWidgetData()// 数据加载的方法
  },
  mounted () {
    this.loadContractsWidgetData();
  },
  computed: {},
  methods: {
    // 合同归档
    contractArchive (row) {
      this.$dialog.show('合同归档提交', ContractArchive, {
        area: ['800px', '70vh']
      }, {
        detail: row
      }).then(res => {
        this.loadContractsWidgetData();
      }).catch(e => {
      });
    },
    // 盖章申请
    sealApplication (row) {
      this.approver.selectRow = row;
      this.approver.show = true;
    },
    // 盖章申请弹窗内：审批人变化时触发
    handleChooseapprover (data) {
      this.$set(this.approver, 'list', data);
    },
    // 盖章申请弹窗内的确定按钮
    confirmApprover () {
      let params = {
        id: this.approver.selectRow.id,
        approver: this.approver.list
      };
      Contracts.addCot(this, params).then(res => {
        this.approver.show = false;
        this.$message.success('申请成功');
        this.loadContractsWidgetData();
      });
    },
    handleClickTotal (type) {
      this.formInline.verifyStatus = type
      this.pageNo = 1
      this.loadContractsWidgetData()
    },
    // 选择签约日期
    selecttime (times) {
      if (times) {
        this.formInline.signingDateFrom = times[0]
        this.formInline.signingDateTo = times[1]
      } else {
        this.formInline.signingDateFrom = ''
        this.formInline.signingDateTo = ''
      }
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this).then(res => {
          this.businesstypeTree = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    businessChange () {
      this.$refs['ref_business'].dropDownVisible = false
    },
    /**
     * 合同管理
     */
    loadContractsWidgetData () {
      let params = {
        ...this.formInline,
        size: this.page_size,
        current: this.pageNo
      }
      return new Promise((resolve, reject) => {
        Contracts.list(this, params).then(res => {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.countInfo = res.data.jsonObject
        }).catch(e => {
          reject(e);
        });
      });
    },
    // 合同立项
    addFromdata () {
      this.$router.push('/Contractsadd');
    },
    // 搜索
    onSubmit () {
      this.pageNo = 1
      this.loadContractsWidgetData()
    },
    // 重置
    resetFromdata () {
      this.formInline = {
        clockInTime: null,
        clockOutTime: null,
        userName: null,
        deptName: null,
        groupName: null
      }
      this.times = ''
      this.pageNo = 1
      this.page_size = 10
      this.loadContractsWidgetData()
    },
    // 分页导航
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadContractsWidgetData()
    },
    handleSizeChange (val) {
      this.page_size = val
      this.loadContractsWidgetData()
    },
    currentChange (val) {
      this.pageNo = val
      this.loadContractsWidgetData()
    },
    // 导出
    exportForm () {
      let params = {
        ...this.formInline,
        size: this.page_size,
        current: this.pageNo
      }
      return new Promise((resolve, reject) => {
        Contracts.ExportFile(this, params, '合同管理明细表.xlsx')
      });
    },
    // 查看
    handleInfo (row) {
      this.$router.push({
        path: '/ContractsDetail',
        query: {
          contractId: row.id
        }
      })
    },
    // 修改
    handleEdit (row) {
      this.$router.push({ path: '/Contractsadd', query: { contractId: row.id, isEdit: true } })
    },
    // 删除
    handleDelete (data) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          id: data.id
        }
        return new Promise((resolve, reject) => {
          Contracts.delete(this, params).then(res => {
            this.$message.success('删除成功！');
            this.loadContractsWidgetData();
          }).catch(e => {
            reject(e);
          });
        });
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.total {
  display: flex;
  align-items: center;
  .total-item {
    padding: 10px;
    cursor: pointer;
    transition: color 0.3s;
    &:hover {
      color: #409eff;
    }
    &.active {
      color: #409eff;
    }
  }
}
</style>
